package com.gitee.wsl.platform.thread

import com.gitee.wsl.concurrent.executor.Executor
import com.gitee.wsl.concurrent.executor.sample.ImmediateExecutor
import java.lang.Runnable
import java.lang.Thread
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicLong

object WorkRunners {

    private val threadFactory = MyThreadFactory()

    @JvmStatic
      fun immediate(): Executor {
        return ImmediateExecutor()
    }

    @JvmStatic
     fun singleThread(): Executor {
        return from(Executors.newSingleThreadExecutor(threadFactory))
    }

    @JvmStatic
     fun fixedThreadPool(n: Int): Executor {
        return from(Executors.newFixedThreadPool(n, threadFactory))
    }

    @JvmStatic
     fun cachedThreadPool(): Executor {
        return from(Executors.newCachedThreadPool(threadFactory))
    }

    @JvmStatic
     fun from(service: ExecutorService): Executor {
        return ExecutorServiceWorkRunner(service)
    }

    private class MyThreadFactory : ThreadFactory {
        private val threadCount = AtomicLong(0)

        override fun newThread(r: Runnable): Thread {
            return Executors.defaultThreadFactory().newThread(r).apply {
                name = "mobius-thread-${threadCount.incrementAndGet()}"
            }
        }
    }
}
